<?php

namespace app\api\controller;

use app\admin\model\Detail;
use app\admin\model\Luck;
use app\admin\model\Otherconfig;
use app\common\controller\Api;
use app\admin\model\Ticket;
use app\admin\model\Userticket;
use app\admin\model\Order;
use app\admin\model\Orderdetail;
use fast\Random;
use think\Db;
use addons\epay\library\Service;


class Buy extends Api 
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * 
     * 水票下单
     * @return void
     */
    public function buyTicket()
    {
        $ticketId = $this->request->post('ticketId',0);
        if(empty($ticketId)) $this->error('fail');
        $ticketDetail = Ticket::find($ticketId);
        if(empty($ticketDetail)) $this->error('fail');
        if(!$ticketDetail['status']) $this->error('fail');
        $orderId = Userticket::generateOrderSn();
        $num = $this->request->post('num',1);
        $source = $this->request->post('source',0);
        Db::startTrans();
        try{
            $model = new Userticket();
            $model->user_id = $this->auth->id;
            $model->ticket_id = $ticketId;
            $model->num = $num;
            $model->source = $source;
            $model->create_time = time();
            $model->list = $ticketDetail['list'];
            if($source == 0) {
                //$model->money = $ticketDetail['money'] * $num;
                $model->money = 0.01;
            }
            $model->order_id = $orderId;
           
            $model->save();
            $insertData = [];
            for($i = 0;$i< $num;$i++){
                $insertData[] = ['origin_id' => $ticketId,'user_id' => $this->auth->id,'source' => 0,'create_time' => time(),'ticket_id' => $model->id,'list' =>  $ticketDetail['list']];
            }
            Db::name('user_ticket_record')->insertAll( $insertData);
            Db::commit();
            $this->success('下单成功',['orderId' => $orderId,'type' => 0]);
            
        }catch(\Exception $e){
            $error = $e->getMessage();
            if(empty($error)) {
                $this->success('下单成功',['orderId' => $orderId,'type' => 0]);
            }
            Db::rollback();
            $this->error('fail');
        }
        
    }
    public function buyProduct()
    {
        $type = $this->request->post('type',1);
        $source = $this->request->post('source',0);//0=直购,1=购物车=2是抽奖
        $luckId = 0;
        if($source == 2) {//如果是抽奖，只支付配送费
            $luckId = $this->request->post('luckId',0);#0 是否有活动商品
            if(empty($luckId)) $this->error('抽奖下单参数错误');//中奖记录ID
            $luckDetail = Luck::find($luckId);
            if(empty($luckDetail )) {
                if(empty($luckId)) $this->error('中奖录不存在');//中奖记录ID
            }
            $detail = Detail::find( $luckDetail['detail_id'] );
            if(!$detail) $this->error('抽奖记录不存在');
            $orderDetail = json_encode([['detail_id' => $detail['id'],'type_id' => $detail['type_id'],'num' => 1 ]]);

        } else {
            $orderDetail = $this->request->post('orderDetail');
            $orderDetail = html_entity_decode($orderDetail);
        }
       
        if(!$orderDetail) {
            $this->error('fail');
        }
        $userBuyTicket = $this->request->post('userBuyTicket',0);#使用购买水票的数量
        $userBuyTicketIds = $this->request->post('userBuyTicketIds','');
        $userActiveTicket = $this->request->post('userActiceTicket',0);#使用抽奖水票的数量
        $userActiveTicketIds = $this->request->post('userActiveTicketIds','');
        $bucket = $this->request->post('bucket',0);#0=无水桶,1=有水桶
        $deliveryType = $this->request->post('deliveryType',0);#0=自提,1=平台送
        $remark = $this->request->post('remark');#备注
        $deliveryTime = $this->request->post('deliveryTime','');#0 是立即配送
        $active = $this->request->post('active',0);#=0是正常商品。=1是抽奖所得
     
        $addresId = $this->request->post('addresId',1);#0 地址
        if(!$addresId)  $this->error('没选地址');
        if($active == 1 && empty($luckId)) {
            $this->error('参数错误');
        }
        $orderId =  Userticket::generateOrderSn('PD');
        Db::startTrans();
        // try{
            $orderDetail = json_decode($orderDetail,true);
            $orderDetail =  Order::addToOrderDetail($orderDetail,$orderId,0);//记录到详情表
            
            if($active == 0) {#如果不是活动商品
                $money = order::caculPrice( $orderDetail['detail'],$userBuyTicketIds, $userActiveTicketIds, $bucket, $active, $orderId,$deliveryType);
            } else {//如果是活动商品
                if($deliveryType == 0) {//如果是自提,白嫖
                    $money = 0;
                } else {
                    $result = Otherconfig::where(['id' => 1])->field('bucket,peisong,count,problict')->find();
                    $money = $result['peisong'] ;
                    if($bucket == 0) {
                        $configDetail =  Otherconfig::find(1);
                        $money +=   $configDetail['bucket']; 
                    } 
                }
            }
            if($money == 0  && $deliveryType == 1) { //价格为0 ，且是平台送
                if( empty($userBuyTicketIds) || empty($userActiveTicketIds))  $this->error('使用水票的数量大于商品数量');
            }
           
            if($type == 0) {
                $this->success('suc',['money' => $money]);
            }
            
            Orderdetail::InsertAll( $orderDetail['detail']);
            $model = new Order();
            $model->user_id = $this->auth->id;
            $model->order_id = $orderId;
            $model->order_detail = json_encode($orderDetail['detail']);
            $model->address_id = $addresId;
            $model->source = $source;
            $model->create_time = time();
            $model->bucket = $bucket;
            $model->user_active_ticket_num = $userActiveTicket;
            $model->use_buy_ticket_num = $userBuyTicket;
            $model->delivery_type = $deliveryType;
            $model->remark = $remark;
            $model->delivery_time = empty($deliveryTime)? date('Y-m-d'):$deliveryTime;
            $model->money = $money;
            $model->code = Random::alnum();
            $model->create_time = time();
            $model->active = $active;
            $model->detail_id = $orderDetail['detailId'];
            $model->num = $active == 0 ? count($orderDetail['detail']):1;//商品数量
            $model->tickek_ids = $userBuyTicketIds;//自购水票
            $model->active_ids = $userActiveTicketIds;//活动水票
            $model->agent_id = $this->auth->getUserinfo()['agent_id'];//代理商的id
            $model->luck_id = $luckId;//代理商的id
            $result = $model->save();
            if(!$result) {
                $this->error($model->getError());
            }
           
           // Db::commit();
            $this->success('suc',['orderId' => $orderId,'type' => 1]);
    
        // } catch(\Exception $e) {
        //     $error = $e->getMessage();
        //     if(empty($error)) {
        //         $this->success('下单成功',['orderId' => $orderId,'type' => 1]);
        //     }
        //    // Db::rollback();
        //     $this->error($e->getFile().$e->getLine().$e->getMessage());
           
        // }
    }
  
    public function pay()
    {
        $type = $this->request->post('type',0);#0是购买水票，，1是购买水
        $orderId = $this->request->post('orderId');
        if($type == 0) {
            $detail = Userticket::where(['order_id' => $orderId])->find();
        } else {
            $detail = Order::where(['order_id' => $orderId])->find();
        }
        if(empty($detail)) $this->error('订单有误');
        $user = $this->auth->getUser();
        $detail['money'] = '0.01';
        $params = [
            'type'         => 'wechat',
            'orderid' => $detail['order_id'],
            'title'        => $type == 0 ?:'水票购买：水购买',
            'amount'       => $detail['money'],
            'method'       => 'miniapp',
            'openid'       => $user['open_id'],
            'auth_code'    => '',
            'notifyurl'    => 'https://www.xingrangshanquan.com/api/notify/notify',
            'returnurl'    => '',
            'custom'       => ['type' => $type]
        ];
        $this->success('suc',Service::submitOrder($params)); 
       
    } 
    
    
    
 
    
    
   
   
   
}
